#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-07-01 13:55:18
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

'''doc string'''

import time
import MySQLdb
import requests


cityList = ['wuhan', 'huangshi', 'shiyan', 'jingzhou', 'yichang',
            'jingmen', 'ezhou', 'xiaogan', 'huanggang', 'xianning',
            'suizhou', 'enshizhou', 'xiangyang']

coor_list = [
    [30.58021825, 114.3813259],
    [30.564366, 114.2658559],
    [30.61624898, 114.2942882],
    [30.54143575, 114.3093671],
    [30.62416066, 114.3866026],
    [30.50523194, 114.228482],
    [30.59240691, 114.311796],
    [30.52047321, 114.3920876],
    [30.63934431, 114.1416751],
    [30.29995375, 113.8784635],
    [30.23059000, 115.07272],
    [30.27338000, 114.84820],
    [30.17270000, 114.952425],
    [30.2066600000, 114.9014300000],
    [30.1548800000, 114.9977300000],
    [32.5056200000, 111.0965700000],
    [32.6480200000, 110.7860800000],
    [32.6611500000, 110.9908800000],
    [32.5681430000, 110.8890940000],
    [112.25461, 30.316766],
    [112.2149885, 30.35659058],
    [112.2886, 30.31095],
    [30.71899585, 111.313579],
    [30.70374086, 111.311342],
    [30.65073765, 111.3673618],
    [30.69927541, 111.2747222],
    [30.77609041, 111.3329567],
    [31.0452700000, 112.2061700000],
    [30.9730300000, 112.2071500000],
    [31.0352200000, 112.2266600000],
    [31.0354600000, 112.1994500000],
    [31.0366000000, 112.1946900000],
    [31.0375700000, 112.1954800000],
    [30.3908500000, 114.8949500000],
    [30.3705500000, 114.9020800000],
    [30.4108800000, 114.8398500000],
    [30.9251100000, 113.9244300000],
    [30.9181200000, 113.6934700000],
    [30.4459000000, 114.8981500000],
    [30.4713500000, 114.9080500000],
    [30.4467300000, 114.8869400000],
    [29.4277900000, 114.7018700000],
    [29.8414600000, 114.3170700000],
    [29.8526900000, 114.2988200000],
    [29.8677500000, 114.3339200000],
    [31.7270900000, 113.3649000000],
    [31.6905900000, 113.3806700000],
    [31.7228310000, 113.3809540000],
    [30.2945000000, 109.5026100000],
    [30.2757200000, 109.4807600000],
    [32.0160570000, 112.1579990000],
    [32.0523100000, 112.1498000000],
    [32.1121200000, 112.1893400000],
    [32.0855500000, 112.2042700000]
]


# 链接到160数据库
def connDB():
    db = MySQLdb.connect('localhost', 'root', '0000', 'pm25')
    return db


# 实时数据
def get_pm25(pm25_type):
    data = []
    for city in cityList:
        url = 'http://www.pm25.in/api/querys/pm2_5.json?city=' + \
            city + '&token=FN6jrgq1p2y14xYGX8pD'  # 5j1znBVAsnSf5xQyNQyq 测试用
        try:
            resource = requests.get(url)
            res_json_list = resource.json()
            if len(res_json_list) == 1:
                return ["Sorry，API Limit"]
            for r in res_json_list:
                name = r['position_name']
                if (name):
                    val = r[pm25_type]
                    data.append(val)
                else:
                    continue
        except requests.ConnectionError as e:
            print e
            return ["Sorry，API Limit"]
        except requests.HTTPError as e:
            print e
            return ["Sorry，API Limit"]
    return data


# 获取当前日期和小时
def getCurrentTime():
    # 记录当前时间
    ct = time.localtime(time.time())
    currentTime = str(ct.tm_year)+str(ct.tm_mon)+str(ct.tm_mday)
    currentHour = ct.tm_hour
    detail = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    return detail, currentTime, currentHour


# 存PM2.5数据到数据库
def storePM25Data():
    i = 1
    while 1:
        # 获取日期和时间
        val = getCurrentTime()
        primary = val[0]
        y = val[1]
        h = val[2]
        print "Start Working now at %s - %s " % (y, h)
        data1 = get_pm25("pm2_5")
        print "Got pm25 ..."
        pm25data = ",".join(str(m) for m in data1)
        data2 = get_pm25('pm2_5_24h')
        print "Got pm25 24H ..."
        pm2524data = ",".join(str(n) for n in data2)
        # 存储数据到数据库
        db = connDB()
        insertDBSQL = "INSERT INTO pm25tab(id, year, hour, pm25, pm2524) VALUES \
        ('%s', '%s', '%s', '%s', '%s')" % (i, y, h, pm25data, pm2524data)
        try:
            cur25 = db.cursor()
            cur25.execute(insertDBSQL)
            db.commit()
            print "sotre 2 db ok..."
        except Exception as e:
            print e
            db.rollback()  # 发生错误时时间回滚
        cur25.close()
        # 隔一个小时取一次数据
        time.sleep(60*60)
        i = i+1
    pass


if __name__ == "__main__":
    storePM25Data()
